package com.twang.stock.controller.common;

import com.twang.stock.entity.User;
import com.twang.stock.mapper.UserMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.UserService;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    // 注入HttpSession
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private UserMapper userMapper;


    public static long TOKEN_TIME=3600*24*1000;

    @GetMapping("/index")
    public ModelAndView index(User user ) throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("pages/login");
        return  modelAndView;
    }

    //接收post的请求,表单提交后,就会调用这个Login()方法
    @PostMapping("/loginIn")
    public String Login(User user,String userName,String password ) throws Exception{
        user.setUserName(userName);
        user.setPassword(password);
        User a = userService.getUser(user);
        if (a!=null){
            // 这边使用了Hutool工具类随机生成不带-的UUID来作为token，也可以JDK自带的UUID生成然后替换掉-
            String token = a.getUserName()+"_"+ HolidayCopy.getHHmmss();
            httpSession.setAttribute(UserService.TOKEN,token);
            redisUtil.set(token,token);
            a.setToken(token);
            userMapper.updateByPrimaryKey(a);
            return "redirect:/index";
        }
        else {
            throw new Exception("登陆失败！");
        }
    }

    @GetMapping("loginOut")
    public String loginOut() {
        Object token = httpSession.getAttribute(UserService.TOKEN);
        // 移除session中的token
        httpSession.removeAttribute(UserService.TOKEN);
        // 移除Redis中的token
        redisUtil.del(token.toString());
        return "redirect:/user/index";
    }
    @GetMapping("register")
    public String register() {
        return "pages/register";
    }

    @PostMapping("addUser")
    public String addUser(User user,String userName,String password ) throws Exception {
        user.setUserName(userName);
        user.setPassword(password);
        User temp = new User();
        temp.setUserName(user.getUserName());
        if (null != userService.getUser(temp)) {
            throw new Exception("用户已存在！");
        }
        userService.addUser(user);
        return Login(user, user.getUserName(), user.getPassword());
    }



}
